import pyices
import logging
import bootstrap
import manager
from threading import Event
    
class Streamer(object):
    """Streamer class that streams to a certain server and mountpoint specified
    with attributes which is a dictionary of ... attributes.
    """
    __metaclass__ = bootstrap.Singleton
    def __init__(self, attributes):
        object.__init__(self)
        self.instance = None
        self.attributes = attributes
        
        self.finish_shutdown = Event()
        
    @property
    def connected(self):
        try:
            return self.instance.connected()
        except (AttributeError):
            return False
    def connect(self):
        self.queue = manager.Queue()
        self.finish_shutdown.clear()
        self.instance = pyices.IcecastStream(self.attributes,
                                        file_method=self.supply_song)
        self.instance.start()
        
    def shutdown(self, force=False):
        """Shuts down the AFK streamer and process"""
        if force:
            self.instance.close()
            logging.info("Stopped AFK Streamer")
        else:
            self.finish_shutdown.set()
            logging.info("Tried stopping AFK Streamer")
        
    def supply_song(self):
        # check for shutdown
        if (self.finish_shutdown.is_set()):
            self.shutdown(force=True)
        else:
            song = self.queue.pop()
            if (song.id == 0L):
                self.queue.clear()
                song = self.queue.pop()
            self.queue.clear_pops()
            # update now playing
            manager.NP.change(song)
            
            return (song.filename, song.metadata)
        return (None, None)